package ar.com.larreta.controlador.server;

import gwtupload.server.UploadAction;
import gwtupload.server.exceptions.UploadActionException;

import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItem;
import org.apache.log4j.Logger;

import ar.com.larreta.procesos.AdministradorDeArchivosSubidos;

public class SubirArchivo extends UploadAction {

	protected static Logger logger = Logger.getLogger(SubirArchivo.class);

	  /**
	   * Override executeAction to save the received files in a custom place
	   * and delete this items from session.  
	   */
	  @Override
	  public String executeAction(HttpServletRequest request, List<FileItem> sessionFiles) throws UploadActionException {
		  
		  
	    String response = "";
	    
	   //int cont = 0;
	    for (FileItem item : sessionFiles) {
	    	
	    	try {
				AdministradorDeArchivosSubidos.getInstancia().agregar(item.getName(), item.getInputStream());
			} catch (IOException e) {
				logger.error("Error al subir archivo", e);
			}	    	
	    	
	      /*if (false == item.isFormField()) {
	        cont++;
	        try {

	          File file = File.createTempFile("upload-", ".bin");
	          item.write(file);
	          
	          
	        } catch (Exception e) {
	          throw new UploadActionException(e);
	        }
	      }*/
	    }
	    
	    /// Remove files from session because we have a copy of them
	    removeSessionFileItems(request);
	    
	    /// Send information of the received files to the client.
	    return "<response>\n" + response + "</response>\n";
	  }
	  
		@Override
		public void checkRequest(HttpServletRequest request) {
			maxSize = maxSize * 10;
			super.checkRequest(request);
		}
}
